//  AppDelegate.m
//  ShowYork
//
//  Created by hxh on 2020/8/24.
//  Copyright © 2020 hxh. All rights reserved.
//

#import "AppDelegate.h"
#import "DFPlayer.h"
#import "DiscoverListViewController.h"
#import "DynamicViewController.h"
#import "RPLaunchScreenViewController.h"
#import "TabBarViewController.h"
#import "XHRemotePushManagar.h"
#import <UMPush/UMessage.h>

#import "ALCCrashHandler.h"

@interface AppDelegate ()<UNUserNotificationCenterDelegate>

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    
    [[NSUserDefaults standardUserDefaults] setObject:@0 forKey:@"isAppPageLoad"];
    [[NSUserDefaults standardUserDefaults]synchronize];
    
    [NSThread sleepForTimeInterval:1];
    
    [[NSUserDefaults standardUserDefaults] setObject:@1 forKey:@"AppTerminate"];
    
    [self setUM];
    // 设置键盘
    [self setIQkeyboard];
    
    [self setNetworkStatus];
    
    [self setRealm];
//    [RPAppManager removeLaunchScreenCacheIfNeeded];
    
    
    UMessageRegisterEntity * entity = [[UMessageRegisterEntity alloc] init];
    //type是对推送的几个参数的选择，可以选择一个或者多个。默认是三个全部打开，即：声音，弹窗，角标
    entity.types = UMessageAuthorizationOptionBadge|UMessageAuthorizationOptionAlert|UMessageAuthorizationOptionSound;
    if (@available(iOS 10.0, *)) {
        [UNUserNotificationCenter currentNotificationCenter].delegate = self;
    } else {
        // Fallback on earlier versions
    }
    [UMessage registerForRemoteNotificationsWithLaunchOptions:launchOptions Entity:entity completionHandler:^(BOOL granted, NSError * _Nullable error) {
        if (granted) {
      
        }else{
            
        }
    }];
    
    NSDictionary *remoteNotification = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
    self.window   = [[UIWindow alloc]init];
    self.window.frame = [UIScreen mainScreen].bounds;
    if (remoteNotification) {
        NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
        formatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
        NSString *dateString = [[NSUserDefaults standardUserDefaults]objectForKey:@"isLoginTime"];
        NSDate *date = [formatter dateFromString:dateString];
        if (![date isToday]) {
            [MobClick event:@"user_day_status_not_login"];
        }
        [self saveLoginTime];
        DiscoverListViewController *listVC = [[DiscoverListViewController alloc]init];
        NavigationViewController *nav = [[NavigationViewController alloc]initWithRootViewController:listVC];
        self.window.rootViewController = nav;
    }else{
        DynamicViewController *dynamicVC = [[DynamicViewController alloc]init];
        self.window.rootViewController = dynamicVC;
    }

    [self.window makeKeyAndVisible];

    self.appActivityStatus = @0;

    [self setHub];
    
    [[DFPlayer sharedPlayer] df_initPlayerWithUserId:nil];
    [DFPlayer sharedPlayer].playMode = DFPlayerModeOrderCycle;
    [DFPlayer sharedPlayer].isObserveWWAN = YES;
    [DFPlayer sharedPlayer].isNeedCache = NO;
    
    NSLog("合并代码");
//    #pragma mark - 崩溃日志
//    [[ALCCrashHandler shareInstance] setDefaultHandler];
//    //发送崩溃日志
//    [[ALCCrashHandler shareInstance] collectionExceptionMessage];

    return YES;
}



- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken{
    
    if (![deviceToken isKindOfClass:[NSData class]]) return;
     const unsigned *tokenBytes = [deviceToken bytes];
     NSString *hexToken = [NSString stringWithFormat:@"%08x%08x%08x%08x%08x%08x%08x%08x",
                           ntohl(tokenBytes[0]), ntohl(tokenBytes[1]), ntohl(tokenBytes[2]),
                           ntohl(tokenBytes[3]), ntohl(tokenBytes[4]), ntohl(tokenBytes[5]),
                           ntohl(tokenBytes[6]), ntohl(tokenBytes[7])];
    [[NSUserDefaults standardUserDefaults]setObject:hexToken forKey:@"CLDeviceToken"];
    [[NSUserDefaults standardUserDefaults]synchronize];
    [UMessage registerDeviceToken:deviceToken];
}

//iOS10以下使用这两个方法接收通知，
-(void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
{
    [UMessage setAutoAlert:NO];
    if([[[UIDevice currentDevice] systemVersion]intValue] < 10){
        [UMessage didReceiveRemoteNotification:userInfo];
        
        completionHandler(UIBackgroundFetchResultNewData);
    }
}
/// 程序已经启动
-(void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler API_AVAILABLE(ios(10.0)){
    NSDictionary * userInfo = notification.request.content.userInfo;
    
    if (notification.request.content.badge.intValue != 0 && [RPAppManager isLogin]) {
        [[NSUserDefaults standardUserDefaults] setObject:notification.request.content.badge forKey:@"messageUnReadCount"];
        
        [[NSUserDefaults standardUserDefaults]setObject:@(1) forKey:@"messageReadStatus"];
        [[NSUserDefaults standardUserDefaults]synchronize];
                
        if ([self.window.rootViewController isKindOfClass:[UITabBarController class]]) {
            [[((UITabBarController *)self.window.rootViewController) tabBar] showBadgeOnItemIndex:3];
        }
    }

    if (@available(iOS 10.0, *)) {
        if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
            //应用处于前台时的远程推送接受
            //关闭U-Push自带的弹出框
            [UMessage setAutoAlert:NO];
            //必须加这句代码
            [UMessage didReceiveRemoteNotification:userInfo];
        }else{
            //应用处于前台时的本地推送接受
        }
    } else {
        // Fallback on earlier versions
    }
    completionHandler(UNNotificationPresentationOptionSound|UNNotificationPresentationOptionBadge|UNNotificationPresentationOptionAlert);
}

-(void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)(void))completionHandler API_AVAILABLE(ios(10.0)){
    
    NSDictionary * userInfo = response.notification.request.content.userInfo;
    
    if (userInfo[@"data"] != nil) {
        MineMessageItemModel *itemModel = [MineMessageItemModel mj_objectWithKeyValues:userInfo[@"data"]];
        [[XHRemotePushManagar sharedXHRemotePushManagar]showRemotePushVCWithData:itemModel];
    }else{
        NSString *url = userInfo[@"url"];
        [[XHPushVCTool sharedXHPushVCTool] pushTargetVCWithUrl:url paramUrl:@""];
    }
   
    if (@available(iOS 10.0, *)) {
        if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
            //应用处于后台时的远程推送接受
            //必须加这句代码
            [UMessage didReceiveRemoteNotification:userInfo];
            
        }else{
            //应用处于后台时的本地推送接受
        }
    } else {
        // Fallback on earlier versions
    }

}

- (void)saveLoginTime{
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    formatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
    NSDate *date = [[NSDate alloc]init];
    NSString *dateString = [formatter stringFromDate:date];
    [[NSUserDefaults standardUserDefaults]setObject:dateString forKey:@"isLoginTime"];
    [[NSUserDefaults standardUserDefaults]synchronize];
}

#pragma mark - 设置友盟
- (void)setUM{
#ifdef DEBUG
    [UMConfigure initWithAppkey:@"5f45faeb113468235fdcf6d3" channel:@"App Dev"];
#else
    [UMConfigure initWithAppkey:@"5f45faeb113468235fdcf6d3" channel:@"App Store"];
#endif
    [UMConfigure setLogEnabled:YES];
    
    [UMSocialGlobal shareInstance].universalLinkDic = @{@(UMSocialPlatformType_WechatSession):@"https://www.showyork.com/app/ddup/wechat/",@(UMSocialPlatformType_WechatTimeLine):@"https://www.showyork.com/app/ddup/wechat/",@(UMSocialPlatformType_QQ):@"https://www.showyork.com/qq_conn/1111175042/"};

    [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_QQ appKey:@"1111175042"/*设置QQ平台的appID*/  appSecret:nil redirectURL:nil];
    [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_WechatTimeLine appKey:@"wxdbd528b500beae83" appSecret:@"2a58dc5e14360cd158b822a23bd0ddc1" redirectURL:@"http://mobile.umeng.com/social"];
    [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_WechatTimeLine appKey:@"wxdbd528b500beae83" appSecret:@"2a58dc5e14360cd158b822a23bd0ddc1" redirectURL:@"http://mobile.umeng.com/social"];
    [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_WechatSession appKey:@"wxdbd528b500beae83" appSecret:@"2a58dc5e14360cd158b822a23bd0ddc1" redirectURL:@"http://mobile.umeng.com/social"];
    [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_Sina appKey:@"1784870066" appSecret:@"d7d1737588b3093b817d452200d8c8d3" redirectURL:@"https://www.showyork.com/"];
    [UMSocialGlobal shareInstance].isUsingHttpsWhenShareContent = NO;
}

- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<UIApplicationOpenURLOptionsKey, id> *)options
{
    //6.3的新的API调用，是为了兼容国外平台(例如:新版facebookSDK,VK等)的调用[如果用6.2的api调用会没有回调],对国内平台没有影响。
    BOOL result = [[UMSocialManager defaultManager]  handleOpenURL:url options:options];
    if (!result) {
        // 其他如支付等SDK的回调
    }
    return result;
}
- (BOOL)application:(UIApplication *)application continueUserActivity:(NSUserActivity *)userActivity restorationHandler:(void (^)(NSArray<id<UIUserActivityRestoring>> * _Nullable))restorationHandler{
    //6.3的新的API调用，是为了兼容国外平台(例如:新版facebookSDK,VK等)的调用[如果用6.2的api调用会没有回调],对国内平台没有影响。
    BOOL result = [[UMSocialManager defaultManager] handleUniversalLink:userActivity options:nil];
    if (!result) {
        // 其他如支付等SDK的回调
    }
    return result;
    
    
    return YES;
}

- (BOOL)application:(UIApplication *)application shouldAllowExtensionPointIdentifier:(UIApplicationExtensionPointIdentifier)extensionPointIdentifier{
    if ([extensionPointIdentifier isEqualToString :@"com.apple.keyboard-service"]){
        return NO;
    }
    return YES;
}

- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation{
    BOOL result = [[UMSocialManager defaultManager] handleOpenURL:url sourceApplication:sourceApplication annotation:annotation];
    if (!result) {
        // 其他如支付等SDK的回调
    }
    return result;
}

#pragma mark -设置键盘
- (void)setIQkeyboard{
   
    [IQKeyboardManager sharedManager].enable = YES;
    [IQKeyboardManager sharedManager].shouldResignOnTouchOutside = YES;
    [IQKeyboardManager sharedManager].enableAutoToolbar = NO;
}
#pragma mark - 设置提醒
- (void)setHub{
    [WHToast setBackColor:[UIColor colorWithRed:15/255.0f green:15/255.0f blue:15/255.0f alpha:1]];
    [WHToast setPadding:15.0f];
  
    [SVProgressHUD hudConfig];
   
}

/// 在这里写支持的旋转方向，为了防止横屏方向，应用启动时候界面变为横屏模式
- (UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window {
    // 可以这么写
    if (self.allowOrentitaionRotation) {
        return UIInterfaceOrientationMaskAllButUpsideDown;
    }
    return UIInterfaceOrientationMaskPortrait;
}

#pragma mark - 设置本地数据库
- (void)setRealm{
    RLMRealmConfiguration *config = [RLMRealmConfiguration defaultConfiguration];
    config.schemaVersion = 11;
    config.migrationBlock = ^(RLMMigration * _Nonnull migration, uint64_t oldSchemaVersion) {
        
    };
    [RLMRealmConfiguration setDefaultConfiguration:config];
    [RLMRealm defaultRealm];
}

- (void)setNetworkStatus{
    // 1.获得网络监控的管理者
    AFNetworkReachabilityManager *manager =  [AFNetworkReachabilityManager sharedManager];
    // 2.设置网络状态改变后的处理
    [manager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
    // 当网络状态改变了, 就会调用这个block
    switch (status) {
        case AFNetworkReachabilityStatusNotReachable: // 没有网络(断网)
            [RPAppManager updateNetworkStatus:@(0)];
            break;
        case AFNetworkReachabilityStatusUnknown:
        case AFNetworkReachabilityStatusReachableViaWWAN: // 手机自带网络
        case AFNetworkReachabilityStatusReachableViaWiFi: // WIFI
            [RPAppManager updateNetworkStatus:@(1)];
            break;
        }
    }];
    // 3.开始监控
    [manager startMonitoring];
}
- (void)applicationDidEnterBackground:(UIApplication *)application{
    NSNumber *count = [[NSUserDefaults standardUserDefaults] objectForKey:@"messageUnReadCount"];
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:count.intValue];
}



@end
